<template>
  <div class="newPatent-container-padding">
    <div v-if="!disabled" class="buttonList">
      <el-button type="primary" @click="handleSaveDraft">保存为草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <el-form
      ref="baseInfoRef"
      :model="formline"
      :rules="rules"
      class="patent-form"
      label-width="auto"
    >
      <el-form-item label="专利号:" prop="patentCode">
        <el-input maxlength="30" v-model="formline.patentCode" />
      </el-form-item>
      <el-form-item label="专利名称:" prop="patentName">
        <el-input maxlength="30" v-model="formline.patentName" />
      </el-form-item>
      <el-form-item label="申请日期:" prop="applyDate">
        <el-date-picker
          v-model="formline.applyDate"
          type="date"
          placeholder="请选择"
          clearable
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="授权日期:" prop="authDate">
        <el-date-picker
          v-model="formline.authDate"
          type="date"
          placeholder="请选择"
          clearable
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="专利权人:" prop="owner">
        <el-input maxlength="30" v-model="formline.owner" />
      </el-form-item>
      <el-form-item label="发明人:">
        <div class="people-list">
          <div
            v-for="(item, index) in formline.inventors"
            :key="index"
            class="people"
          >
            <el-input maxlength="30" v-model="item.name" placeholder="姓名" />
            <el-input
              maxlength="30"
              v-model="item.mobile"
              placeholder="手机号"
            />
            <el-input
              maxlength="30"
              v-model="item.employeeCode"
              placeholder="员工编号"
            />
            <el-input
              maxlength="30"
              v-model="item.contributeProportion"
              placeholder="贡献率 %"
            />
            <el-button
              v-if="index !== 0"
              type="danger"
              :icon="Delete"
              circle
              @click="removeInventor(index)"
            />
          </div>
          <div class="last">
            <el-button type="primary" text :icon="Plus" @click="addInventor">
              增加发明人
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="完成单位:" prop="completeUnit">
        <el-input maxlength="30" v-model="formline.completeUnit" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { reactive, withDefaults, defineProps, onMounted } from 'vue'
  import { Delete, Plus } from '@element-plus/icons-vue'
  import { addPatentInfo, getPatentInfo, updatePatent } from '@/api/property'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { useRoute } from 'vue-router'
  import { postDraftBoxCreate } from '@/api/project/drafts'

  const props = withDefaults(
    defineProps<{
      disabled?: boolean
    }>(),
    {
      disabled: false,
    }
  )
  const route = useRoute()
  const { closeTabNavigate } = useCloseTabNavigate()
  const formline = reactive({
    patentCode: '',
    patentName: '',
    applyDate: '',
    authDate: '',
    owner: '',
    inventors: [
      { name: '', mobile: '', employeeCode: '', contributeProportion: '' },
    ],
    completeUnit: '',
  })

  const patentId = ref('')

  onMounted(() => {
    const id = (route.query.id as string) ?? ''
    patentId.value = id
    if (id) {
      getPatentInfo({ id: id, getType: 2 }).then((res) => {
        for (const key in res.data) {
          // if (key === 'inventors') {

          // }
          formline[key] = res.data[key]
        }
      })
    }

    try {
      const inputList = document.querySelectorAll('input.el-input__inner')
      const maxLength = 30
      inputList.forEach((input: any) => {
        input.maxLength = maxLength
      })
    } catch (error) {}
  })

  const addInventor = () => {
    formline.inventors.push({
      name: '',
      mobile: '',
      employeeCode: '',
      contributeProportion: '',
    })
  }
  const removeInventor = (index: number) => {
    formline.inventors.splice(index, 1)
  }

  const rules = reactive({
    // patentCode: [{ required: true, message: '请输入', trigger: 'blur' }],
    // patentName: [{ required: true, message: '请输入', trigger: 'blur' }],
  })

  // 草稿
  const handleSaveDraft = async () => {
    baseInfoRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const params = {
            id: route.query.id || '',
            type: 'PATENT',
            submitJson: JSON.stringify({
              ...formline,
              draftBoxId: route.query?.id || '',
            }),
          }
          const res: any = await postDraftBoxCreate(params)
          if (res && res.code === 0) {
            ElMessage.success('保存草稿成功')
            closeTabNavigate({ name: 'Patent' })
          } else {
            ElMessage.error(`保存草稿失败: ${res.msg || '未知错误'}`)
          }
        } catch (e) {
          console.error('保存草稿失败', e)
        }
      }
    })
  }

  const baseInfoRef = ref()
  const submit = () => {
    // if (formline.inventors[0].name == '') {
    //   ElMessage.warning('发明人不能为空')
    //   return
    // }
    baseInfoRef.value.validate(async (valid: boolean) => {
      if (valid) {
        if (patentId.value) {
          const params = {
            id: patentId.value,
            ...formline,
          }
          updatePatent(params).then((res) => {
            ElMessage.success('修改成功')
            closeTabNavigate({ name: 'Patent' })
          })
        } else {
          const params = {
            ...formline,
          }
          addPatentInfo(params).then((res) => {
            ElMessage.success('增加成功')
            closeTabNavigate({ name: 'Patent' })
          })
        }
      }
    })
  }
</script>

<style scoped lang="scss">
  $margin-bottom: 20px;

  .buttonList {
    display: flex;
    justify-content: end;
    padding-bottom: $margin-bottom;
    border-bottom: 1px solid #edeff2;
    margin-bottom: $margin-bottom;
  }

  .patent-form {
    width: 60%;
    // margin: 0 auto;
  }

  .people {
    display: grid;
    grid-template-columns: repeat(4, 1fr) 0.5fr;
    grid-column-gap: 20px;
  }

  .people + .people {
    margin-top: $margin-bottom;
  }

  .last {
    margin-top: $margin-bottom;
  }
</style>
